const http = require('http'),
      url = require('url'),
      func = require('./common.js');
var RES,_GET,_POST,h;
exports.main = (req,res) =>{
    var tool = require(req.bind.dir+'/module/emma.js')
    var HTML = tool.require('html');
    _GET = req.bind.__GET;
    _POST = req.bind.__POST;
    RES = res;
    h = new HTML();
    h.isMobile(req,tool);
    h.load({'title':'HTTP || '+Math.random()*100000});
    //req.setEncoding('utf-8');//无效相比=  h.appHead('<meta charset="utf-8">');
    h.appHead('<meta charset="utf-8">');
    var html = '';
    html += func.navlist(func.udata(req.url,'app'));
    if(_GET && _GET['isPost']) html += postHttpForm();
    else if(_POST == null) html += httpgetForm();
    html += '<h4>http.globalAgent</h4>'+pobj(http.globalAgent);
    h.appBody(html);
    res.write(h.getHtml());
    echo('<p>回调函数难以返回数据！(异步)</p>');
    var isfeek = lkserver();
    //  清除函数缓存
    func.clear(__dirname+'/common.js');
    return isfeek;
}
function httpgetForm(){
    var host = _GET['host'];
    var xhtml = '<h4>URL请求</h4>';
    var opt = [
        {type:'url',name:'host',required:'required',value:host,placeholder:'输入请求url地址（http：//）',style:'width:400px;'},
        {type:'submit',value:'提交'}
    ];
    xhtml += `<form action="" method="get"><a href="/node/http?isPost=Y">post</a><br>${h.text(opt)}</form>`;
    return xhtml;
}
//  post数据
function postHttpForm(){
    var xhtml = '';
    
    var form = h.text({type:'url',name:'purl',required:'required',value:'',placeholder:'输入请求url地址（http：//）',style:'width:400px;'})+'<br>';
    form += h.text({type:'text',name:'pdata',value:'',placeholder:'输入post数据,为空时请求方式为get方式',style:'width:400px;'})+'<br>';
    form += h.text({type:'submit',value:'提交'});
    xhtml += `<form action="" method="post"><a href="/node/http?isPost=Y">get</a><br>${form}</form>`;
    return xhtml;
}
function lkserver(){
    var rxhtml = '',
        json = _GET;
    if(json && json['host']){
        //  可获取对象 socket,headers,connection,trailers,client,req,
        http.get(json['host'], (res) => {
            var code = res.statusCode,
                hd
            ;
            console.log(`Got response: ${code}`);
            // consume response body
            //console.log(res);
            res.resume();
            rxhtml += pobj(res.headers);
            rxhtml += '<h4>socket</h4>'+pobj(res.socket);
            rxhtml += '<h4>connection</h4>'+pobj(res.connection);
            rxhtml += '<h4>trailers</h4>'+pobj(res.trailers);
            rxhtml += '<h4>client</h4>'+pobj(res.client);
            rxhtml += '<h4>req</h4>'+pobj(res.req);
            
            echo(rxhtml);
            RES.end();
        }).on('error', (e) => {
            console.log(`Got error: ${e.message}`);RES.end();
        });
        return true;
    }else if(_POST){
        rxhtml += '<h4>post数据源</h4>'+pobj(_POST);
        echo(rxhtml);

        var postData = _POST['pdata'];
        var options = {
            hostname: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(postData)
            }
        };
        var udata = url.parse(_POST['purl']);//console.log(udata);
        options['hostname'] = udata['host'];
        options['port'] = (udata['port']? udata['port']:80);
        options['path'] = udata['path'];
        if(_POST['method']){
            options['method'] = (_POST['method'] == 'GET' || _POST['method'] == 'get')? 'GET':'POST';
        }
        if(!postData) options['method'] = 'GET';
        console.log(options);
        var req = http.request(options, (res) => {
            var h1 = `STATUS: ${res.statusCode}`;
            h1 += `HEADERS: ${JSON.stringify(res.headers)}`;
            res.setEncoding('utf8');
            echo(h1);
            res.on('data', (chunk) => {
                echo(`<div><h4>POST 响应</h4><div>BODY: <pre>${chunk}</pre></div></div>`);
            });
            res.on('end', () => {
                console.log('No more data in response.')
                RES.end();
            });
        });
        req.on('error', (e) => {
            console.log(`problem with request: ${e.message}`);
        });
        // write data to request body
        req.write(postData);
        req.end();
        return true;
    }else return null;
}
function echo(xhtml){
    if(typeof(xhtml) == 'undefined' || xhtml == null || xhtml == '') return false;
    if(typeof(RES) != 'object') return false;
    RES.write(xhtml);
}
//  打印object数据对象
function pobj(data,all)
{
    var xhtml = '';
    if(typeof(data) == 'object'){
        for(var k in data){
            if(typeof(data[k]) != 'object' && typeof(data[k]) != 'function') xhtml += `<li>${k} : ${data[k]}</li>`;
            else if(all) xhtml += `<li><br>${k} : ${data[k]}</li>`;
        }
    }
    return xhtml;
}
//  递归调用： 打印系统 string= 递归调用造成“内存溢出”   RangeError: Maximum call stack size exceeded
function print_r(data){
    var xhtml = '';
    if(typeof(data) == 'object'){
        for(var k in data){
            //xhtml += `<li>${k} : `;
            xhtml += '<li>'+k+' : ';
            if(typeof(data[k]) == 'string') xhtml += data[k];
            //else if(typeof(data[k]) == 'object') xhtml += '<ul style="list-style:none;">'+print_r(data[k])+'</ul>';
            else if(typeof(data[k]) == 'object') xhtml += '<ul style="list-style:none;">'+arguments.callee(data[k])+'</ul>';
            xhtml += '</li>';
        }
        if(xhtml) xhtml =  `<ul style="list-style:none;">${xhtml}</ul>`;
    }
    echo(xhtml);
    return xhtml;
}